/*
    Copyright (C) 2015 Apple Inc. All Rights Reserved.
    See LICENSE.txt for this sample’s licensing information
    
    Abstract:
    A view controller that demonstrates how to present a search controller's search bar within a navigation bar.
*/

import UIKit

class SearchBarEmbeddedInNavigationBarViewController: SearchControllerBaseViewController, UISearchBarDelegate,UISearchDisplayDelegate{
    // MARK: Properties
    
    // `searchController` is set in viewDidLoad(_:).
    var searchController: UISearchController!
    var searchBar: UISearchBar!
    var isHighversion: Bool!
    

    // MARK: View Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create the search results view controller and use it for the UISearchController.
        let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier(SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
        
    // Create the search controller and make it perform the results updating.
        
        
        
        var str:NSString = UIDevice.currentDevice().systemVersion
        var version:Float = str.floatValue
        if version >= 8.0
        {
            isHighversion = true
            searchController = UISearchController(searchResultsController: searchResultsController)
            searchController.searchResultsUpdater = searchResultsController
            searchController.hidesNavigationBarDuringPresentation = false
            
            // Configure the search controller's search bar. For more information on how to configure
            // search bars, see the "Search Bar" group under "Search".
            searchController.searchBar.searchBarStyle = .Minimal
            searchController.searchBar.placeholder = NSLocalizedString("Search", comment: "")
            searchController.searchBar.showsCancelButton = true;
            for v in searchController.searchBar.subviews[0].subviews{
                if ( v.isKindOfClass(UIButton) ){
                    let cancelButton = v as! UIButton;
                    cancelButton.setTitle("Cancel", forState: UIControlState.Normal);
                    cancelButton.tintColor = UIColor.whiteColor();
                    cancelButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
                }
                if (v.isKindOfClass(UITextField))
                {
                    let  searchField = v as! UITextField
                    searchField.tintColor = UIColor.whiteColor()
                    searchField.textColor = UIColor.whiteColor()
                }
            }
            
            searchController.searchBar.delegate = self
            
            // Include the search bar within the navigation bar.
            navigationItem.titleView = searchController.searchBar
            definesPresentationContext = true
        }
        else
        {
            
           /* var searcharray:NSArray
            var userDefault = NSUserDefaults.standardUserDefaults()
            searchhistory.addObject("3")
            searcharray = searchhistory
            userDefault.setObject(searcharray, forKey: "search history")
            userDefault.synchronize()*/
            searchBar = UISearchBar(frame: CGRectMake(0, 0, 80, 30))
            configureSearchBar()
            navigationItem.titleView = searchBar
            isHighversion = false
            
        }
        
    }
    
    //add by py searchbar config
    
    
   /*
    func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool
    {
        println("test1")
        return true
    }
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        
    }
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.setShowsCancelButton(false, animated: true)
    }
    
    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchBar.becomeFirstResponder()
        searchBar.setShowsCancelButton(true, animated: true)
    }
    
    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        
    }
    
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        return true
    }
    
    func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
        return true
    }
    
    */
    
    
    func configureSearchBar()
    {
        searchBar.searchBarStyle = .Minimal
        searchBar.placeholder = NSLocalizedString("Search", comment: "")
        searchBar.showsCancelButton = true
        searchBar.delegate = self
       // searchBar.showsBookmarkButton = true
        for v in searchBar.subviews[0].subviews{
            if ( v.isKindOfClass(UIButton) ){
                let cancelButton = v as! UIButton;
                cancelButton.setTitle("Cancel", forState: UIControlState.Normal);
                cancelButton.tintColor = UIColor.whiteColor();
                cancelButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
            }
            if (v.isKindOfClass(UITextField))
            {
                let  searchField = v as! UITextField
                searchField.tintColor = UIColor.whiteColor()
                searchField.textColor = UIColor.whiteColor()
            }
        }
    }
    
    func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
        let scopes = self.searchDisplayController!.searchBar.scopeButtonTitles as! [String]
        let selectedScope = scopes[self.searchDisplayController!.searchBar.selectedScopeButtonIndex] as String
      //  self.filterContentForSearchText(searchString, scope: selectedScope)
        return true
    }
    
    func searchDisplayController(controller: UISearchDisplayController,
        shouldReloadTableForSearchScope searchOption: Int) -> Bool {
            let scope = self.searchDisplayController!.searchBar.scopeButtonTitles as! [String]
       //     self.filterContentForSearchText(self.searchDisplayController!.searchBar.text, scope: scope[searchOption])
            return true
    }
    
    
    func searchBarSearchButtonClicked( searchBar: UISearchBar)
    {
        
        var searcharray:NSArray
        var userDefault = NSUserDefaults.standardUserDefaults()
        if (isHighversion == true)
        {
            searchhistory.addObject(searchController.searchBar.text)
        }
        else
        {
            searchhistory.addObject(searchBar.text)
        }
        searcharray = searchhistory
        userDefault.setObject(searcharray, forKey: "search history")
        userDefault.synchronize()
      //  println( searchController.searchBar.text)
    
    }
    @IBAction func goBack(sender: AnyObject) {
       
        self.navigationController?.popViewControllerAnimated(true)
        rootController.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
  
    }
    
    
    
    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
       // footerView.backgroundColor = UIColor.blackColor()
        var x = tableView.frame.size.width
        x -= 120
        x = x/2
        var searchresetbutton:UIButton = UIButton(frame: CGRectMake(x, 0, 120, 30))
        searchresetbutton.titleLabel?.font = UIFont.boldSystemFontOfSize(15)
        searchresetbutton.setTitleColor(UIColor.grayColor(),forState:UIControlState.Normal)
        searchresetbutton.setTitle("清空搜索记录", forState:UIControlState.Normal)
        searchresetbutton.setBackgroundImage(UIImageView(image: UIImage(named: "清空搜索记录.png")).image, forState: UIControlState.Normal)
        searchresetbutton.addTarget(self, action:Selector("searchresetbuttonClicked:"), forControlEvents:UIControlEvents.TouchDown)
        
        if(searchhistory.count != 0)
        {
            footerView.addSubview(searchresetbutton)
        }
        return footerView
    }
    
    func searchresetbuttonClicked(sender:UIButton)

    {
        
        searchhistory.removeAllObjects()
        var searcharray:NSArray = searchhistory
        var userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(searcharray, forKey: "search history")
        userDefault.synchronize()
        tableView.reloadData()
        
    }
    
    
  
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //searchString =  tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
        
        var str = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
        
        GlobalData.searchstring = str!
       //searchString = str!
        // println(tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text)

        /*
        let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier(SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
        
        // Create the search controller and make it perform the results updating.
        searchControllerbase = UISearchController(searchResultsController: searchResultsController)
        searchControllerbase.searchResultsUpdater = searchResultsController
        searchControllerbase.hidesNavigationBarDuringPresentation = false
        
        // Configure the search controller's search bar. For more information on how to configure
        // search bars, see the "Search Bar" group under "Search".
        searchControllerbase.searchBar.searchBarStyle = .Minimal
        searchControllerbase.searchBar.placeholder = NSLocalizedString("Search", comment: "")
        
        searchControllerbase.searchBar.delegate = self
        
        var str = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
        // println(tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text)
        println(str)
        //  searchResultsController.baseResult(str!)        // Include the search bar within the navigation bar.
        navigationItem.titleView = searchControllerbase.searchBar
        
        definesPresentationContext = true
        self.navigationController?.pushViewController(searchControllerbase, animated: true)*/
    }

    
    
    /*
    override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 40.0
    }
    */
    
    /*
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "showDetail"  {
            let destinationController = segue.destinationViewController as! QuickSearchResultViewController
            destinationController.searchString = searchString //传值
        }  
        
    }
    */
}
